﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Docx2Epub.Epub
{
    class EPubCoverWriter : WriterBase
    {
        private string coverPath;
        private EPubMetadatas metadatas;
        private string outputPath;

        public EPubCoverWriter(string outputPath, EPubMetadatas metadatas)
        {
            this.outputPath = outputPath;
            this.coverPath = Path.Combine(outputPath, "OEBPS", "cover.xhtml");
            this.metadatas = metadatas;
        }

        internal void WriteOut()
        {
            var imagesDir = Path.Combine(outputPath, "OEBPS", "images");
            Directory.CreateDirectory(imagesDir);
            File.Copy(metadatas.CoverImagePath,
                Path.Combine(imagesDir, "cover" + Path.GetExtension(metadatas.CoverImagePath)), 
                true);

            XElement doc = XElement.Load(coverPath);

            // set title
            doc.XPathSelectElement("/xhtml:head/xhtml:title", nsmgr).Value = metadatas.Title;

            // set image name
            doc.XPathSelectElement("/xhtml:body/xhtml:div/xhtml:img", nsmgr)
                .Attribute("src").Value = "images/cover" + Path.GetExtension(metadatas.CoverImagePath);

            using (FileStream fs = new FileStream(coverPath, FileMode.Create, FileAccess.Write))
            using (StreamWriter sr = new StreamWriter(fs))
                doc.Save(sr);
        }
    }
}
